﻿
#include "TowerDevicesController.h"

#include <QDebug>
#include <QDesktopServices>
#include <QUrl>

#include "global/SettingsHelper.h"
#include "Utils.h"

#define LINE_TEMP_SETTINGS_NAME "line_temp_settings.xlsx"
#define GROUNDED_SETTINGS_NAME "grounded_settings.xlsx"

///
/// |-------------------------   64 Bytes ----------------------------------------------------|
/// |-------------------------------位置信息(64字节)--------------------------------------------|
const static QChar Base1 = 0x0080;
const static char Base1Offset = 0x20;
///
/// |-------------------------   8 Bytes  ----------------------------------------------------|
/// |---  ID （4 Bytes)-------------------|---系数（2 Bytes)-------|----预留(2 Bytes)-----------|
const static QChar Base2 = 0x1010;
const static char Base2Offset = 0x04;
///
/// |-------------------------    32 Bytes  --------------------------------------------------|
/// |---温度 （2 Bytes)---|---电流（2 Bytes)---|---故障位 （2 Bytes)---|------预留(26 Bytes)------|
const static QChar Base3 = 0x1240;
const static char Base3Offset = 0x10;

/// |-------------------------   64 Bytes ----------------------------------------------------|
/// |-------------------------------位置信息(64字节)--------------------------------------------|
const static QChar Base4 = 0x0000;
const static char Base4Offset = 0x20;

///
/// |-------------------------   8 Bytes  ----------------------------------------------------|
/// |---  ID （4 Bytes)-------------------|-----系数 （2Bytes）--|----预留(2 Bytes)-------------|
const static QChar Base5 = 0x1000;
const static char Base5Offset = 0x04;

///
/// |-------------------------    32 Bytes  --------------------------------------------------|
/// |-温度(2Bytes)-|--电池电压()--|---电流（2 Bytes)---|---故障位 （2 Bytes)---|---预留(26 Bytes)--|
const static QChar Base6 = 0x1200;
const static char Base6Offset = 0x10;

TowerDevicesController::TowerDevicesController(QObject *parent)
    : QObject{parent}
    , _serverAddress(1)
    , line_temp_info_(SettingsHelper::Instance()->rootDir().absolutePath()+"/"+LINE_TEMP_SETTINGS_NAME)
    , grounded_info_(SettingsHelper::Instance()->rootDir().absolutePath()+"/"+GROUNDED_SETTINGS_NAME)
    , debugger_(new SerialDebugger("Settings.ini",this))
{
   initAllGroups();
}

TowerDevicesController::~TowerDevicesController(){
    link_->deleteLater();
}

void TowerDevicesController::initAllGroups()
{
    for(auto i = 0 ;i <64; i++) {
        auto group =   new LineTempFactGroup(this);
        group->describeInfoAddress(Base1.unicode()+ Base1Offset*i);
        group->idAndFactorAddress(Base2.unicode()+ Base2Offset*i);
        group->dataValeAddres(Base3.unicode()+ Base3Offset*i);
        lineTempGroups_.append(group);
    }
    for(auto i = 0 ;i < 4; i++) {
        auto group =   new GroundedFactGroup(this);
        group->describeInfoAddress(Base4.unicode()+ Base4Offset*i);
        group->idAndFactorAddress(Base5.unicode()+ Base5Offset*i);
        group->dataValeAddres(Base6.unicode()+ Base6Offset*i);
        groundedGroups_.append(group);
    }
}

void TowerDevicesController::insertSettingsHeader(QXlsx::Document &xlsx)
{
    xlsx.write(QString("A1"),QStringLiteral("设备编号"));
    xlsx.write(QString("B1"),QStringLiteral("设备系数"));
    xlsx.write(QString("C1"),QStringLiteral("位置信息"));
}

bool TowerDevicesController::createSettingsFile(Device_Type type,
                                            int address_count,
                                            const QString &id,
                                            const QString &factor,
                                            const QString &desc)
{
    QXlsx::Document xlsx;
    this->insertSettingsHeader(xlsx);
    bool isSequential = (id == "")?true:false;
    double res_factor = (factor == "")? 1.0 :factor.toDouble();
    if(type == Device_Type::LineTemp) {
        for(int i = 0 ;i < address_count;i++){
            if(isSequential){
             xlsx.write(QString("A%1").arg(i+2),i+1);
            }
            else{
             xlsx.write(QString("A%1").arg(i+2),id);
            }
            xlsx.write(QString("B%1").arg(i+2),res_factor);
            xlsx.write(QString("C%1").arg(i+2),desc);
        }
        return xlsx.saveAs(line_temp_info_.absoluteFilePath());
    }
    else if(type == Device_Type::Grounded) {
        for(int i = 0 ;i < address_count;i++){
            if(isSequential){
             xlsx.write(QString("A%1").arg(i+2),i+1);
            }
            else{
             xlsx.write(QString("A%1").arg(i+2),id);
            }
            xlsx.write(QString("B%1").arg(i+2),res_factor);
            xlsx.write(QString("C%1").arg(i+2),desc);
        }
        return  xlsx.saveAs(grounded_info_.absoluteFilePath());
    }
    return false;
}

bool TowerDevicesController::isfileExist(Device_Type type)
{
    if(type == Device_Type::LineTemp){
        return line_temp_info_.exists();
    }
    else if(type == Device_Type::Grounded){
        return grounded_info_.exists();
    }
    return false;
}

bool TowerDevicesController::openSettingsFile(Device_Type  type)
{
    if(isfileExist(type)){
        if(type == Device_Type::LineTemp) {
          return QDesktopServices::openUrl(QUrl::fromLocalFile(line_temp_info_.absoluteFilePath()));
        }
        else if(type == Device_Type::Grounded){
          //qDebug() <<QUrl::fromLocalFile(grounded_info_.absoluteFilePath());
          return QDesktopServices::openUrl(QUrl::fromLocalFile(grounded_info_.absoluteFilePath()));
        }
    }
    return false;
}

bool TowerDevicesController::isSettingsFileVaild(Device_Type type)
{
    switch (type) {
    case LineTemp:{
        QXlsx::Document xlsx(line_temp_info_.absoluteFilePath());
        bool idIsVaild = xlsx.read(QString("A1")).toString() == QStringLiteral("设备编号");
        bool factor =  xlsx.read(QString("B1")).toString() == QStringLiteral("设备系数");
        bool desc = xlsx.read(QString("C1")).toString() == QStringLiteral("位置信息");
        int rowCount = xlsx.dimension().rowCount();
        for(int i = 1; i< rowCount ;i++){
          QString id = xlsx.read(QString("A%1").arg(rowCount)).toString();
          if(id.size() > 4){
             return false;
          }
          bool ok;
          double factor = xlsx.read(QString("B%1").arg(rowCount)).toDouble(&ok);
          if(!ok){
             return false;
          }
          QString dest = xlsx.read(QString("C%1").arg(rowCount)).toString();
          if(dest.size() > 32) {
             return false;
          }
        }
        return true;
    }
    break;
    case Grounded:{
        QXlsx::Document xlsx(line_temp_info_.absoluteFilePath());
        bool idIsVaild = xlsx.read(QString("A1")).toString() == QStringLiteral("设备编号");
        bool factor =  xlsx.read(QString("B1")).toString() == QStringLiteral("设备系数");
        bool desc = xlsx.read(QString("C1")).toString() == QStringLiteral("位置信息");
        int rowCount = xlsx.dimension().rowCount();
        for(int i = 1; i< rowCount ;i++){
          QString id = xlsx.read(QString("A%1").arg(rowCount)).toString();
          if(id.size() > 4){
             return false;
          }
          bool ok;
          double factor = xlsx.read(QString("B%1").arg(rowCount)).toDouble(&ok);
          if(!ok){
             return false;
          }
          QString dest = xlsx.read(QString("C%1").arg(rowCount)).toString();
          if(dest.size() > 32) {
             return false;
          }
        }
        return true;
    }
    break;
    default:
        break;
    }
    return false;

}

bool TowerDevicesController::connected() const
{
    if(link_){
        return connected_;
    }
    return false;
}

void TowerDevicesController::setConnected(bool state)
{
    connected_ = state;
    emit connectedChanged(state);
}

bool TowerDevicesController::connectLink(const QString & port_name,
                             int baud,int data_bits,
                             int stop_bits,int parity)
{
    if(link_){
        link_->deleteLater();
        link_ = nullptr;
    }
    link_= LinkManager::Instance()->creatModbusRtuLink(port_name,baud,data_bits,stop_bits,parity);

    QObject::connect(link_,&LinkInterface::connectedChanged,[this](bool state){
        setConnected(state);
    });

    QObject::connect(link_,&ModbusRtuLink::readData,this,
                     &TowerDevicesController::handleLineTempModbusProto);

    QObject::connect(link_,&ModbusRtuLink::readUnitFinished,[this](){
        readTaskRemain--;
        if(readTaskRemain == 0 || readTaskRemain < 0){
            emit readSettingsFinished();
        }
    });

    QObject::connect(link_,&ModbusRtuLink::writeUnitFinished,[this](){
        writeTaskRemain--;
        if(writeTaskRemain == 0 || writeTaskRemain < 0){
            emit writeSettingsFinished();
        }
    });

    bool conn_res  = link_->connect();
    if(!conn_res) {
        link_->deleteLater();
        link_ = nullptr;
        return false;
    }
    return true;
}

bool TowerDevicesController::connectDebuggerLink(const QString & port_name,
                                     int baud,int data_bits,
                                     int stop_bits,int parity)
{

    if(debuggerLink_) {
        debuggerLink_->deleteLater();
        debuggerLink_ = nullptr;
    }
    debuggerLink_= LinkManager::Instance()->createSerialLink(port_name,baud,data_bits,stop_bits,parity);

    QObject::connect(debuggerLink_,&SerialLink::bytesReceived,[this](LinkInterface* link, QByteArray data){
        auto format  = getFormatDataString("#recv");
        emit readDebuggerMsg(format+" "+data);
    });

    bool conn_res  = debuggerLink_->connect();
    if(!conn_res) {
        debuggerLink_->deleteLater();
        debuggerLink_ = nullptr;
        return false;
    }
    return true;
}

void TowerDevicesController::setDebuggerMode(bool isHex)
{
    this->isHexDisplay_ = isHex;
}

void TowerDevicesController::disConnectDebuggerLink()
{
    if(debuggerLink_){
        debuggerLink_->disConnect();
    }
}

void TowerDevicesController::writeBytesToDebugger(const QString &data)
{
    if(debuggerLink_){
        debuggerLink_->writeBytes(data.toLatin1());
        auto format  = getFormatDataString("#send");
        emit writeDebggerMsg(format+" "+data);
    }
}

void TowerDevicesController::disConnectedLink()
{
    if(link_){
        this->disconnect(link_,&ModbusRtuLink::readData,this,
                         &TowerDevicesController::handleLineTempModbusProto);
        link_->disConnect();
        link_->deleteLater();
        link_ = nullptr;
    }
}

bool TowerDevicesController::exportXlsxFile(Device_Type type,const QString & file_name)
{
    QXlsx::Document xlsx(file_name);
    insertExportFileHeader(type,xlsx);
    switch (type) {
    case LineTemp:
    {
        for(auto i =  0 ;i < lineTempGroups_.size();i ++) {
          xlsx.write(QString("A%1").arg(i+2),(lineTempGroups_[i]->id()->valueString()));
          xlsx.write(QString("B%1").arg(i+2),(lineTempGroups_[i]->factor()->valueString()));
          xlsx.write(QString("C%1").arg(i+2),(lineTempGroups_[i]->lineTemp()->valueString()));
          xlsx.write(QString("D%1").arg(i+2),(lineTempGroups_[i]->current()->valueString()));
          xlsx.write(QString("E%1").arg(i+2),(lineTempGroups_[i]->errorCode()->valueString()));
          xlsx.write(QString("F%1").arg(i+2),(lineTempGroups_[i]->describeInfo()->valueString()));
        }
    }
    break;
    case Grounded:{
        for(auto i = 0 ;i < groundedGroups_.size();i ++) {
          xlsx.write(QString("A%1").arg(i+2),(groundedGroups_[i]->id()->valueString()));
          xlsx.write(QString("B%1").arg(i+2),(groundedGroups_[i]->factor()->valueString()));
          xlsx.write(QString("C%1").arg(i+2),(groundedGroups_[i]->temp()->valueString()));
          xlsx.write(QString("D%1").arg(i+2),(groundedGroups_[i]->current()->valueString()));
          xlsx.write(QString("E%1").arg(i+2),(groundedGroups_[i]->aPoleResistor()->valueString()));
          xlsx.write(QString("F%1").arg(i+2),(groundedGroups_[i]->bPoleResistor()->valueString()));
          xlsx.write(QString("G%1").arg(i+2),(groundedGroups_[i]->cPoleResistor()->valueString()));
          xlsx.write(QString("H%1").arg(i+2),(groundedGroups_[i]->dPoleResistor()->valueString()));
          xlsx.write(QString("I%1").arg(i+2),(groundedGroups_[i]->totalResistance()->valueString()));
          xlsx.write(QString("J%1").arg(i+2),(groundedGroups_[i]->current()->valueString()));
          xlsx.write(QString("K%1").arg(i+2),(groundedGroups_[i]->strikeCount()->valueString()));
          xlsx.write(QString("L%1").arg(i+2),(groundedGroups_[i]->strikeTime()->valueString()));
          xlsx.write(QString("M%1").arg(i+2),(groundedGroups_[i]->strikeCurrent()->valueString()));
          xlsx.write(QString("N%1").arg(i+2),(groundedGroups_[i]->describeInfo()->valueString()));
        }
    }
    default:
        break;
    }
    return xlsx.saveAs(file_name);
}

QString TowerDevicesController:: getFormatDataString(const QString &custom)
{
    QDateTime currentDateTime = QDateTime::currentDateTime();
    QString dataString = currentDateTime.toString("yyyy-MM-dd hh:mm:ss");
    QString formatString = QString("[%1%2]").arg(dataString).arg(custom);
    return formatString;
}

void TowerDevicesController::byteArrayToIntVector(QVector<quint16>&vec,QByteArray &msg)
{
    for(int i =0 ;i< msg.size();i+=2){
       auto charh = ((quint16)msg[i] << 8) ;
       auto charl = (quint8)msg[i+1];
       quint16 result = charh | charl;
       vec.append(result);
    }
}

void TowerDevicesController::clearGroupsData(Device_Type type)
{
    switch (type) {
        case LineTemp:{
           for(auto i : lineTempGroups_){
                i->id()->setValue("");
                i->lineTemp()->setValue(0);
                i->factor()->setValue(0);
                i->current()->setValue(0);
                i->errorCode()->setValue(false);
                i->describeInfo()->setValue("");
           }
        }
    break;
        case Grounded:
        {
           for(auto i:groundedGroups_){
                i->id()->setValue("");
                i->factor()->setValue(0);
                i->temp()->setValue(0);
                i->batteryVoltage()->setValue(0);
                i->totalResistance()->setValue(0);
                i->aPoleResistor()->setValue(0);
                i->bPoleResistor()->setValue(0);
                i->cPoleResistor()->setValue(0);
                i->dPoleResistor()->setValue(0);
                i->current()->setValue(0);
                i->strikeCount()->setValue(0);
                i->strikeTime()->setValue("");
                i->strikeCurrent()->setValue(0);
                i->describeInfo()->setValue("");
           }
        }
    break;
    default:
       break;
    }
}

bool TowerDevicesController::writeSettingsToDevice(Device_Type type)
{
    if(type == LineTemp && isfileExist(LineTemp)) {
        QXlsx::Document xlsx(line_temp_info_.absoluteFilePath());
        int row = xlsx.dimension().lastRow()-1;
        writeTaskRemain  = row*2;
        for(int i = 0 ; i < row ; i++){
            //设置终端位置信息
            ///因为qtmodbus写入是异步没法同步判断///
            ///这里做一个信号槽连接任务任务开始时候写入任务量当任务量完成写入提示结束发送
            QThread::msleep(100);
            setDescribeInfo(Base1.unicode()+ Base1Offset*i,xlsx.read(QString("C%1").arg(i+2)).toString());
            //设置ID和系数
            QThread::msleep(100);
            setIdAndFactor(Base2.unicode()+ Base2Offset*i,
                                       xlsx.read(QString("A%1").arg(i+2)).toString(),
                                       xlsx.read(QString("B%1").arg(i+2)).toDouble());
        }
        return true;
    }
    else if(type == Grounded && isfileExist(Grounded)) {
        QXlsx::Document xlsx(grounded_info_.absoluteFilePath());
        int row = xlsx.dimension().lastRow()-1;
        writeTaskRemain  = row*2;
        for(int i = 0;  i < row ; i++){
            //设置终端位置信息
            QThread::msleep(100);
            setDescribeInfo(Base4.unicode()+ Base4Offset*i,xlsx.read(QString("C%1").arg(i+2)).toString());
            //设置ID和系数
            QThread::msleep(100);
            setIdAndFactor(Base5.unicode()+ Base5Offset*i,
                                   xlsx.read(QString("A%1").arg(i+2)).toString(),
                                   xlsx.read(QString("B%1").arg(i+2)).toDouble());
        }
    }
    return false;
}

void TowerDevicesController::readSettingsFromDevice(Device_Type type)
{
    clearGroupsData(type);
    if(type == Device_Type::LineTemp) {
        readTaskRemain   = 64*3;
        for(auto i= 0 ; i < 64 ; i++){
            QThread::msleep(100);
            readDescribeInfo(Base1.unicode());
            QThread::msleep(100);
            readIdAndFactor(Base2.unicode()+ Base2Offset*i);
            QThread::msleep(100);
            readValueData(Base3.unicode()+ Base3Offset*i);
        }
    }
    if(type == Device_Type::Grounded) {
        readTaskRemain   = 4*3;
        for(auto i= 0 ; i < 4 ; i++){
            QThread::msleep(100);
            readDescribeInfo(Base4.unicode());
            QThread::msleep(100);
            readIdAndFactor(Base5.unicode()+ Base5Offset*i);
            QThread::msleep(100);
            readValueData(Base6.unicode()+ Base6Offset*i);
        }
    }
}

LineTempFactGroup *TowerDevicesController::getLineTempGroupByIndex(int index)
{
    if(index > 63){
       return nullptr;
    }
    return lineTempGroups_[index];
}

GroundedFactGroup *TowerDevicesController::getGroundedGroupByIndex(int index)
{
    if(index > 3){
       return nullptr;
    }
    return groundedGroups_[index];
}

void TowerDevicesController::insertExportFileHeader(Device_Type type , QXlsx::Document & xlsx)
{
    switch (type) {
    case LineTemp:{
       xlsx.write("A1",QStringLiteral("ID"));
       qDebug() << "TEST";
       xlsx.write("B1",QStringLiteral("系数"));
       xlsx.write("C1",QStringLiteral("线温"));
       xlsx.write("D1",QStringLiteral("电流"));
       xlsx.write("E1",QStringLiteral("故障码"));
       xlsx.write("F1",QStringLiteral("描述信息"));
    }
    break;
    case  Grounded:{
       xlsx.write("A1",QStringLiteral("ID"));
       xlsx.write("B1",QStringLiteral("系数"));
       xlsx.write("C1",QStringLiteral("温度"));
       xlsx.write("D1",QStringLiteral("电池电压"));
       xlsx.write("E1",QStringLiteral("A电阻"));
       xlsx.write("F1",QStringLiteral("B电阻"));
       xlsx.write("G1",QStringLiteral("C电阻"));
       xlsx.write("H1",QStringLiteral("D电阻"));
       xlsx.write("I1",QStringLiteral("总电阻值"));
       xlsx.write("J1",QStringLiteral("电流"));
       xlsx.write("K1",QStringLiteral("雷击计数"));
       xlsx.write("L1",QStringLiteral("雷击时间"));
       xlsx.write("M1",QStringLiteral("雷击电流"));
       xlsx.write("N1",QStringLiteral("描述信息"));
    }
    default:
       break;
    }
}

void TowerDevicesController::setDescribeInfo(int startAddress, const QString& dest)
{
    if(connected()){
        //加上换行回车吧
        QByteArray utf8Data{};
        utf8Data.append(dest.toLocal8Bit());
        utf8Data.resize(64);
        QVector<quint16> value{};
        byteArrayToIntVector(value,utf8Data);
        link_->writeUnit(QModbusDataUnit::HoldingRegisters,serverAddress(),startAddress,value);
    }
}

void TowerDevicesController::setIdAndFactor(int startAddress, const QString &id,const double factor)
{
    if(connected()){
        if(id.size() > 4){
           return ;
        }
        QVector<quint16>value{0,0,0,0};
        QByteArray id_bytes{};
        if(id.size()< 4){
            QString id_str = id.rightJustified(4,'0');
            id_bytes = id_str.toLatin1();
            qDebug()<<id_bytes;
        }
        else{
          id_bytes = id.left(4).toLatin1();
        }
       value[0] =  Utils::bytesToQuint16(id_bytes.at(0),id_bytes.at(1),QSysInfo::BigEndian);
       value[1] =  Utils::bytesToQuint16(id_bytes.at(2),id_bytes.at(3),QSysInfo::BigEndian);
       value[2] =  static_cast<quint16>(factor);
       value[3] = 0;
       link_->writeUnit(QModbusDataUnit::HoldingRegisters,serverAddress(),startAddress,value);
    }
}

void TowerDevicesController::readDescribeInfo(int startAddress)
{
    if(connected()){
       link_->readUnit(QModbusDataUnit::HoldingRegisters,serverAddress(),startAddress,32);
    }
}

void TowerDevicesController::readIdAndFactor(int startAddress)
{
    if(connected()){
       link_->readUnit(QModbusDataUnit::HoldingRegisters,serverAddress(),startAddress,4);
    }
}

void TowerDevicesController::readValueData(int startAddress)
{
    if(connected()){
       link_->readUnit(QModbusDataUnit::HoldingRegisters,serverAddress(),startAddress,16);
    }
}

void TowerDevicesController::handleLineTempModbusProto(int serverAddress,
                                                       int startAddress,
                                                       const QModbusDataUnit &unit)
{
    for(auto i :lineTempGroups_) {
        bool isDescribeInfo = (i->describeInfoAddress() == startAddress);
        bool isIdAndFactor =  (i->idAndFactorAddress() == startAddress);
        bool isDataValue =  (i->dataValeAddres() == startAddress);
        //解析位置信息
        if(isDescribeInfo){
            if(unit.valueCount() == 32){
                QByteArray resValue{};
                for(auto data :unit.values()) {
                   auto bytes  = Utils::quint16ToByteArray(data);
                   resValue.append(bytes);
                   QString descrStr =  QString::fromLocal8Bit(resValue);
                   i->describeInfo()->setValue(descrStr);
                }
            }
        }
        else if(isIdAndFactor){
            if(unit.valueCount() == 4) {
                QVector<quint16> id {};
                id.append(unit.value(0));
                id.append(unit.value(1));
                auto bytes  = Utils::quint16VecToByteArray(id);
                i->id()->setValue(QString::fromLatin1(bytes));
                quint16 factor = unit.value(2);
                i->factor()->setValue(factor);
            }
        }
        else if(isDataValue){
            if(unit.valueCount() == 16) {
                int temp =  unit.value(0);
                i->lineTemp()->setValue(temp);
                int current = unit.value(1);
                i->current()->setValue(current);
                int errorCode = unit.value(2);
            }
        }
    }
    for(auto i :groundedGroups_)
    {
        bool isDescribeInfo = (i->describeInfoAddress() == startAddress);
        bool isIdAndFactor  = (i->idAndFactorAddress() == startAddress);
        bool isDataValue    = (i->dataValeAddres() == startAddress);
        //解析位置信息
        if(isDescribeInfo){
            if(unit.valueCount() == 32){
                QByteArray resValue{};
                for(auto data :unit.values()) {
                   auto bytes  = Utils::quint16ToByteArray(data);
                   resValue.append(bytes);
                   QString descrStr =  QString::fromLocal8Bit(resValue);
                   i->describeInfo()->setValue(descrStr);
                }
            }
        }
        else if(isIdAndFactor){
            if(unit.valueCount() == 4) {
                QVector<quint16> id {};
                id.append(unit.value(0));
                id.append(unit.value(1));
                auto bytes  = Utils::quint16VecToByteArray(id);
                i->id()->setValue(QString::fromLatin1(bytes));
                quint16 factor = unit.value(2);
                i->factor()->setValue(factor);
            }
        }
        else if(isDataValue) {
            if(unit.valueCount() == 16){
               auto temp =  unit.value(0);
               i->temp()->setValue(temp);
               auto vol = unit.value(1);
               i->batteryVoltage()->setValue(vol);
               auto totalR = unit.value(2);
               i->totalResistance()->setValue(totalR);
               auto apoleR = unit.value(3);
               i->aPoleResistor()->setValue(apoleR);
               auto bpoleR = unit.value(4);
               i->bPoleResistor()->setValue(bpoleR);
               auto cpoleR = unit.value(5);
               i->cPoleResistor()->setValue(cpoleR);
               auto dpoleR = unit.value(6);
               i->dPoleResistor()->setValue(dpoleR);
               auto current = unit.value(7);
               i->current()->setValue(current);
               auto skrikeCount = unit.value(8);
               i->strikeCount()->setValue(skrikeCount);
               QVector<quint16> skrikeTimeValue{unit.value(9),
                                                unit.value(10),
                                                unit.value(11),
                                                unit.value(12)};
               auto skrikeTimeBytes = Utils::quint16VecToByteArray(skrikeTimeValue);
               i->strikeTime()->setValue(QString::fromLatin1(skrikeTimeBytes));
               auto skrikeCurrent = unit.value(13);
               i->strikeCurrent()->setValue(skrikeCurrent);
            }
        }
    }
}







